{% extends "base.html" %}

{% block title %}XBot管理后台 - 插件管理{% endblock %}

{% block page_title_icon %}<i class="bi bi-puzzle page-title-icon"></i>{% endblock %}
{% block page_title %}插件管理{% endblock %}

{% block content %}
<!-- 操作区域 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="搜索插件..." id="searchInput">
            <button class="btn btn-primary" type="button" id="searchBtn">
                <i class="bi bi-search"></i> 搜索
            </button>
        </div>
    </div>
    <div class="col-md-4 text-end">
        <button class="btn btn-primary" id="refreshBtn">
            <i class="bi bi-arrow-clockwise"></i> 刷新列表
        </button>
    </div>
</div>

<!-- 插件统计卡片 -->
<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-primary-light">
                    <i class="bi bi-puzzle text-primary"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">总插件数</div>
                    <div class="fw-bold fs-4" id="totalPlugins">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-success-light">
                    <i class="bi bi-toggle-on text-success"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">已启用插件</div>
                    <div class="fw-bold fs-4" id="enabledPlugins">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-danger-light">
                    <i class="bi bi-toggle-off text-danger"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">已禁用插件</div>
                    <div class="fw-bold fs-4" id="disabledPlugins">--</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 插件列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">插件列表</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>插件名称</th>
                        <th>描述</th>
                        <th>版本</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="pluginsTableBody">
                    <tr>
                        <td colspan="5" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2 text-muted">加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 插件配置模态框 -->
<div class="modal fade" id="pluginConfigModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">插件配置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="pluginConfigContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2">加载中...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveConfigBtn">保存配置</button>
            </div>
        </div>
    </div>
</div>

{% block scripts %}
<script>
// 全局变量
let pluginsList = [];
let currentPlugin = null;
let pluginConfigModal = null;
let currentConfig = {};

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化模态框
    pluginConfigModal = new bootstrap.Modal(document.getElementById('pluginConfigModal'));
    
    // 加载插件列表
    loadPlugins();
    
    // 绑定事件
    document.getElementById('refreshBtn').addEventListener('click', loadPlugins);
    document.getElementById('searchBtn').addEventListener('click', searchPlugins);
    document.getElementById('searchInput').addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            searchPlugins();
        }
    });
    
    document.getElementById('saveConfigBtn').addEventListener('click', savePluginConfig);
});

// 加载插件列表
async function loadPlugins() {
    const tableBody = document.getElementById('pluginsTableBody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2 text-muted">加载中...</p>
            </td>
        </tr>
    `;
    
    try {
        const response = await fetch('/api/plugins');
        const data = await response.json();
        
        if (data.success) {
            pluginsList = data.data || [];
            displayPlugins(pluginsList);
            updateStats(pluginsList);
        } else {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-4">
                        <div class="text-danger">
                            <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                            <p>加载失败: ${data.message || '未知错误'}</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载插件列表失败:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-danger">
                        <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                        <p>加载失败: ${error.message || '网络错误'}</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 显示插件列表
function displayPlugins(plugins) {
    const tableBody = document.getElementById('pluginsTableBody');
    
    if (!plugins || plugins.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-muted">
                        <i class="bi bi-puzzle fs-3 mb-3"></i>
                        <p>暂无插件数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let html = '';
    plugins.forEach(plugin => {
        const name = plugin.name || '未命名插件';
        const description = plugin.description || '无描述';
        const version = plugin.version || '1.0.0';
        const enabled = plugin.enabled || false;
        
        html += `
            <tr>
                <td class="fw-bold">${escapeHtml(name)}</td>
                <td>${escapeHtml(description)}</td>
                <td>${escapeHtml(version)}</td>
                <td>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" id="switch-${name}" 
                            ${enabled ? 'checked' : ''} onchange="togglePlugin('${name}', this.checked)">
                        <label class="form-check-label" for="switch-${name}">
                            ${enabled ? '<span class="text-success">已启用</span>' : '<span class="text-muted">已禁用</span>'}
                        </label>
                    </div>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="openPluginConfig('${name}')">
                        <i class="bi bi-gear"></i> 配置
                    </button>
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
}

// 更新统计信息
function updateStats(plugins) {
    document.getElementById('totalPlugins').textContent = plugins.length;
    
    // 计算启用和禁用的插件数量
    const enabled = plugins.filter(plugin => plugin.enabled).length;
    const disabled = plugins.length - enabled;
    
    document.getElementById('enabledPlugins').textContent = enabled;
    document.getElementById('disabledPlugins').textContent = disabled;
}

// 搜索插件
function searchPlugins() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    
    if (!searchTerm) {
        displayPlugins(pluginsList);
        return;
    }
    
    const filteredPlugins = pluginsList.filter(plugin => {
        const name = (plugin.name || '').toLowerCase();
        const description = (plugin.description || '').toLowerCase();
        
        return name.includes(searchTerm) || description.includes(searchTerm);
    });
    
    displayPlugins(filteredPlugins);
}

// 切换插件启用状态
async function togglePlugin(pluginName, enabled) {
    try {
        const response = await fetch(`/api/plugins/${pluginName}/toggle`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ enabled })
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 更新本地插件列表
            const plugin = pluginsList.find(p => p.name === pluginName);
            if (plugin) {
                plugin.enabled = enabled;
                
                // 更新状态标签
                const label = document.querySelector(`label[for="switch-${pluginName}"]`);
                if (label) {
                    label.innerHTML = enabled ? 
                        '<span class="text-success">已启用</span>' : 
                        '<span class="text-muted">已禁用</span>';
                }
                
                // 更新统计信息
                updateStats(pluginsList);
            }
            
            // 显示成功消息
            showToast('成功', `插件 ${pluginName} 已${enabled ? '启用' : '禁用'}`, 'success');
        } else {
            // 恢复开关状态
            const switchEl = document.getElementById(`switch-${pluginName}`);
            if (switchEl) {
                switchEl.checked = !enabled;
            }
            
            // 显示错误消息
            showToast('错误', `操作失败: ${data.message || '未知错误'}`, 'danger');
        }
    } catch (error) {
        console.error(`切换插件 ${pluginName} 状态失败:`, error);
        
        // 恢复开关状态
        const switchEl = document.getElementById(`switch-${pluginName}`);
        if (switchEl) {
            switchEl.checked = !enabled;
        }
        
        // 显示错误消息
        showToast('错误', `操作失败: ${error.message || '网络错误'}`, 'danger');
    }
}

// 打开插件配置
async function openPluginConfig(pluginName) {
    const configContent = document.getElementById('pluginConfigContent');
    configContent.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">加载中...</p>
        </div>
    `;
    
    // 保存当前插件名称
    currentPlugin = pluginName;
    
    // 显示模态框
    pluginConfigModal.show();
    
    try {
        const response = await fetch(`/api/plugins/${pluginName}/config`);
        const data = await response.json();
        
        if (data.success) {
            // 保存当前配置
            currentConfig = data.data || {};
            
            // 生成配置表单
            let html = `<h5 class="mb-4">${escapeHtml(pluginName)} 插件配置</h5>`;
            
            if (Object.keys(currentConfig).length === 0) {
                html += `
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>
                        该插件没有可配置的选项
                    </div>
                `;
            } else {
                html += `<form id="pluginConfigForm">`;
                
                // 遍历配置项
                for (const key in currentConfig) {
                    const value = currentConfig[key];
                    const type = typeof value;
                    
                    html += `<div class="mb-3">`;
                    html += `<label for="config-${key}" class="form-label">${escapeHtml(key)}</label>`;
                    
                    if (type === 'boolean') {
                        html += `
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" 
                                    id="config-${key}" name="${key}" ${value ? 'checked' : ''}>
                            </div>
                        `;
                    } else if (type === 'number') {
                        html += `
                            <input type="number" class="form-control" id="config-${key}" 
                                name="${key}" value="${value}">
                        `;
                    } else if (Array.isArray(value)) {
                        html += `
                            <textarea class="form-control" id="config-${key}" name="${key}" 
                                rows="3">${value.join('\n')}</textarea>
                            <div class="form-text">每行输入一个值</div>
                        `;
                    } else if (type === 'object') {
                        html += `
                            <textarea class="form-control" id="config-${key}" name="${key}" 
                                rows="5">${JSON.stringify(value, null, 2)}</textarea>
                            <div class="form-text">使用JSON格式</div>
                        `;
                    } else {
                        html += `
                            <input type="text" class="form-control" id="config-${key}" 
                                name="${key}" value="${escapeHtml(value.toString())}">
                        `;
                    }
                    
                    html += `</div>`;
                }
                
                html += `</form>`;
            }
            
            configContent.innerHTML = html;
        } else {
            configContent.innerHTML = `
                <div class="text-center text-danger">
                    <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                    <p>加载失败: ${data.message || '未知错误'}</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载插件配置失败:', error);
        configContent.innerHTML = `
            <div class="text-center text-danger">
                <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                <p>加载失败: ${error.message || '网络错误'}</p>
            </div>
        `;
    }
}

// 保存插件配置
async function savePluginConfig() {
    if (!currentPlugin) return;
    
    const form = document.getElementById('pluginConfigForm');
    if (!form) return;
    
    // 收集表单数据
    const newConfig = {};
    
    // 遍历当前配置项
    for (const key in currentConfig) {
        const value = currentConfig[key];
        const type = typeof value;
        const element = document.getElementById(`config-${key}`);
        
        if (!element) continue;
        
        if (type === 'boolean') {
            newConfig[key] = element.checked;
        } else if (type === 'number') {
            newConfig[key] = parseFloat(element.value);
        } else if (Array.isArray(value)) {
            newConfig[key] = element.value.split('\n').filter(line => line.trim() !== '');
        } else if (type === 'object') {
            try {
                newConfig[key] = JSON.parse(element.value);
            } catch (e) {
                alert(`${key} 的JSON格式无效`);
                return;
            }
        } else {
            newConfig[key] = element.value;
        }
    }
    
    try {
        const response = await fetch(`/api/plugins/${currentPlugin}/config`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newConfig)
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 隐藏模态框
            pluginConfigModal.hide();
            
            // 显示成功消息
            showToast('成功', `插件 ${currentPlugin} 配置已保存`, 'success');
        } else {
            showToast('错误', `保存失败: ${data.message || '未知错误'}`, 'danger');
        }
    } catch (error) {
        console.error('保存插件配置失败:', error);
        showToast('错误', `保存失败: ${error.message || '网络错误'}`, 'danger');
    }
}

// 显示提示消息
function showToast(title, message, type = 'info') {
    // 创建toast容器
    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(toastContainer);
    }
    
    // 创建toast元素
    const toastId = `toast-${Date.now()}`;
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    toast.setAttribute('id', toastId);
    
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                <strong>${escapeHtml(title)}</strong>: ${escapeHtml(message)}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    // 初始化并显示toast
    const bsToast = new bootstrap.Toast(toast, {
        autohide: true,
        delay: 3000
    });
    bsToast.show();
    
    // 自动移除toast元素
    toast.addEventListener('hidden.bs.toast', function() {
        toast.remove();
    });
}

// 转义HTML
function escapeHtml(text) {
    if (!text) return '';
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
</script>

<style>
.icon-wrapper {
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 1.5rem;
}

.bg-primary-light {
    background-color: rgba(67, 97, 238, 0.1);
}

.bg-success-light {
    background-color: rgba(16, 185, 129, 0.1);
}

.bg-danger-light {
    background-color: rgba(220, 53, 69, 0.1);
}

/* 开关样式美化 */
.form-check-input:checked {
    background-color: #0d6efd;
    border-color: #0d6efd;
}

.form-switch .form-check-input {
    width: 2.5em;
    margin-left: -2.8em;
}

.form-switch .form-check-input:focus {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");
}

.form-switch .form-check-input:checked {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
}
</style>
{% endblock %}
{% endblock %} 